package com.ming.mallchat.common.user.service.impl;

import com.ming.mallchat.common.common.constant.RedisKey;
import com.ming.mallchat.common.common.utils.JwtUtils;
import com.ming.mallchat.common.common.utils.RedisUtils;
import com.ming.mallchat.common.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    public static final int TOKEN_EXPIRE_DAY = 3;
    public static final int TOKEN_RENEWA_DAYS = 1;
    @Autowired
    private JwtUtils jwtUtils;


    /**
     * 刷新token有效期
     *
     * @param token
     */
    @Override
    @Async
    public void renewalTokenIfNecessary(String token) {
        Long uid = getValidUid(token);
        String tokenKey = getUserTokenKey(uid);
        Long expireDays = RedisUtils.getExpire(tokenKey, TimeUnit.DAYS);
        if (expireDays == -2) {//不存在的key
            return;
        }
        if (expireDays < TOKEN_RENEWA_DAYS) {
            RedisUtils.expire(getUserTokenKey(uid), TOKEN_EXPIRE_DAY, TimeUnit.DAYS);
        }
    }

    /**
     * 获取token
     *
     * @param id
     * @return {@link String}
     */
    @Override
    public String login(Long id) {
        String token = jwtUtils.createToken(id);
        RedisUtils.set(getUserTokenKey(id), token, TOKEN_EXPIRE_DAY, TimeUnit.DAYS);
        return token;
    }

    /**
     * 如果token有效，返回uid
     *
     * @param token
     * @return
     */
    @Override
    public Long getValidUid(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return null;
        }
        String oldToken = RedisUtils.getStr(getUserTokenKey(uid));
        return Objects.equals(token, oldToken) ? uid : null;
    }

    private String getUserTokenKey(Long id) {
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING, id);
    }
}
